#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;

vector<int> requests; // 请求序列
vector<int> chose;    // 选择序列
bool visited[100]{0};
int n;             // 编号1~n
int start;         // 磁头起始位置
int totalMove = 0; // 总移动次数

int SSTF()
{
    vector<int> tmp = requests;
    tmp.push_back(start);
    std::sort(tmp.begin(), tmp.end());

    int i, count = 1;
    for (i = 0; i <= n; i++)
    {
        if (tmp[i] == start)
        {
            visited[i] = true;
            break;
        }
    }

    chose.push_back(start);
    while (count <= n)
    {
        int left = i - 1;
        int right = i + 1;
        while (left >= 0 && visited[left])
            left--;
        while (right <= n && visited[right])
            right++;

        int min;
        if (left < 0 || visited[left])
            min = tmp[right] - tmp[i], i = right;
        else if (right > n || visited[right])
            min = tmp[i] - tmp[left], i = left;
        else
        {
            min = std::min(tmp[i] - tmp[left], tmp[right] - tmp[i]);
            i = (tmp[i] - tmp[left] > tmp[right] - tmp[i] ? right : left);
        }

        visited[i] = true;
        totalMove += min;
        chose.push_back(tmp[i]);
        count++;
    }

    return totalMove;
}

int main()
{
    cout << "请输入请求序列长度："; // 8
    cin >> n;

    cout << "请输入" << n << "个请求：" << endl;
    for (int i = 0; i < n; i++) // 98 183 37 122 14 124 65 67
    {
        int tmp;
        cin >> tmp;
        requests.push_back(tmp);
    }

    cout << "请输入磁头起始位置："; // 53
    cin >> start;

    cout << "SSTF总步数：";
    cout << SSTF() << endl; // 236
    for (int val : chose)
        cout << val << " ";
    cout << endl;

    return 0;
}

/*
请输入请求序列长度：8
请输入8个请求：
98 183 37 122 14 124 65 67
请输入磁头起始位置：53
SSTF总步数：236
53 65 67 37 14 98 122 124 183
*/